#include <iostream>
#include <functional>
#include <unordered_map>
#include "../include/muduo/net/TcpServer.h"
#include "../include/muduo/net/EventLoop.h"
#include "../include/muduo/net/TcpConnection.h"

class TranslateServer
{
public:
    TranslateServer(int port)
        : _server(&_baseloop, muduo::net::InetAddress("0.0.0.0", port), "TranslateServer", muduo::net::TcpServer::kReusePort)
    {
        _server.setConnectionCallback(std::bind(&TranslateServer::onConnection, this, std::placeholders::_1));
        _server.setMessageCallback(std::bind(&TranslateServer::onMessage, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3));
    }

    void start() {
        _server.start();
        _baseloop.loop();
    }

private:
    // 在连接建立成功以及关闭的时候被调用
    void onConnection(const muduo::net::TcpConnectionPtr& conn) {
        // 新连接建立成果时的回调函数
        if (conn->connected() == true) {
            std::cout << "新建连接成功! \n";
        } else {
            std::cout << "新建连接失败! \n";
        }
    }

    std::string translate(const std::string &str) {
        static std::unordered_map<std::string, std::string> dict_map = {
            {"hello", "你好"},
            {"Hello", "你好"},
            {"你好", "hello"}
        };
        auto it = dict_map.find(str);
        if (it == dict_map.end()) {
            return "没听懂!!!";
        }

        return it->second;
    }

    void onMessage(const muduo::net::TcpConnectionPtr& conn, muduo::net::Buffer* buf, muduo::Timestamp) {
        // 通信连接收到请求时的回调函数
        // 1. 从 buf 中把请求数据读取出来
        std::string str = buf->retrieveAllAsString();
        // 2. 调用 translate 接口进行翻译
        std::string resp = translate(str);
        // 3. 对客户端进行响应
        conn->send(resp);
    }
private:
    muduo::net::EventLoop _baseloop;
    muduo::net::TcpServer _server;
};

int main()
{
    TranslateServer server(8080);
    server.start();
    return 0;
}